package com.example.book.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author pangxichen
 * 配置文件加载类
 */
public class PropertiesLoader {

    private static final Logger logger = LoggerFactory.getLogger(Constants.class);

    private static ResourceLoader resourceLoader = new DefaultResourceLoader();

    private static Properties properties;

    public PropertiesLoader(String... path) {
        properties = load(path);
    }


    /**
     * 取值：以系统的配置优先。去不到系统值，取出配置文件的值
     * @param key
     * @return
     */
    private String getValue(String key) {
        String systemKey = System.getProperty(key);
        if (StringUtils.isNotBlank(systemKey)) {
            return systemKey;
        }

        if (properties.containsKey(key)) {
            return properties.getProperty(key);
        }
        return null;
    }


    /**
     * 取值方法
     * @param key
     * @return
     */
    public String getKey(String key) {
        String value = getValue(key);
        if (value != null) {
            return value;
        }
        return null;
    }

    /**
     * 加载配置文件
     *
     * @param path
     * @return
     * @throws IOException
     */
    private Properties load(String... path) {
        Properties properties = new Properties();

        for (String localtion : path) {
            InputStream inputStream = null;
            try {
                Resource resource = resourceLoader.getResource(localtion);
                inputStream = resource.getInputStream();
                properties.load(inputStream);
            } catch (IOException io) {
                logger.info("Could not load properties from path:" + localtion + "," + io.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException io) {
                    logger.info("close inputStream failed");
                }
            }
        }
        return properties;
    }

}
